package com.itheima.controller;

import com.itheima.common.R;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("common")
public class CommonController {

    //注入配置文件中的数据
    @Value("${reggie.path}")
    private String basePath;

    /**
     * 文件上传
     */
    @PostMapping("upload")
    public R<String> upLoad(MultipartFile file) throws IOException {
        //创建文件对象
        File dir = new File(basePath);
        //判断文件是否存在该目录
        if (!dir.exists()) {
            //不存在，创建该文件夹
            dir.mkdirs();
        }
        //原始文件名称
        String originalFilename = file.getOriginalFilename();
        //拼接形成新的随机数
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
        //将临时文件转存到指定位置
        file.transferTo(new File(basePath + fileName));
        return R.success(fileName);
    }

    /**
     * 文件下载
     */
    @GetMapping("download")
    public void downLoad(String name, HttpServletResponse response) throws Exception {
        FileInputStream is = new FileInputStream(basePath + name);
        ServletOutputStream os = response.getOutputStream();
        IOUtils.copy(is, os);
        is.close();
    }
}
